package com.ruoyi.web.controller.aggregation;

import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.system.domain.aggregation.AggQrcode;
import com.ruoyi.system.service.aggregation.IQrCodeService;

/**
 * 二维码Controller
 * 
 * @author ruoyi
 * @date 2025-01-01
 */
@RestController
@RequestMapping("/agg/qrcode")
public class QrCodeController
{
    @Autowired
    private IQrCodeService qrCodeService;

    /**
     * 生成商家聚合二维码
     */
    @GetMapping("/generate")
    public AjaxResult generate(@RequestParam Long merchantId)
    {
        try
        {
            String qrCodePath = qrCodeService.generateMerchantQrCode(merchantId);
            return AjaxResult.success(qrCodePath);
        }
        catch (Exception e)
        {
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * 生成App下载二维码
     */
    @GetMapping("/download")
    public AjaxResult download()
    {
        try
        {
            String qrCodePath = qrCodeService.generateDownloadQrCode();
            return AjaxResult.success(qrCodePath);
        }
        catch (Exception e)
        {
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * 处理二维码扫描
     */
    @Anonymous
    @GetMapping("/scan")
    public AjaxResult scan(@RequestParam String code)
    {
        try
        {
            // 解析二维码内容
            // 如果是 merchant://123 格式，返回商家ID
            if (code.startsWith("merchant://"))
            {
                Long merchantId = Long.parseLong(code.replace("merchant://", ""));
                
                // 记录扫码次数
                qrCodeService.recordScan(merchantId);
                
                return AjaxResult.success(merchantId);
            }
            
            // 如果是App下载链接格式：https://xxx.com/download?merchantId=123&from=qr
            if (code.contains("merchantId=") && code.contains("from=qr"))
            {
                try
                {
                    // 提取merchantId参数
                    String[] parts = code.split("merchantId=");
                    if (parts.length > 1)
                    {
                        String merchantIdStr = parts[1].split("&")[0];
                        Long merchantId = Long.parseLong(merchantIdStr);
                        
                        // 记录扫码次数
                        qrCodeService.recordScan(merchantId);
                        
                        return AjaxResult.success(merchantId);
                    }
                }
                catch (Exception e)
                {
                    // 解析失败，返回原始内容
                }
            }
            
            return AjaxResult.success(code);
        }
        catch (Exception e)
        {
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * 聚合码分页列表
     */
    @GetMapping("/page")
    public AjaxResult page(
            @RequestParam(defaultValue = "1") Long pageIndex,
            @RequestParam(defaultValue = "10") Long pageSize,
            @RequestParam(required = false) String merchantName,
            @RequestParam(required = false) String startTime,
            @RequestParam(required = false) String endTime)
    {
        try
        {
            PageHelper.startPage(pageIndex.intValue(), pageSize.intValue());
            
            AggQrcode query = new AggQrcode();
            query.setMerchantName(merchantName);
            if (startTime != null)
            {
                query.getParams().put("beginTime", startTime);
            }
            if (endTime != null)
            {
                query.getParams().put("endTime", endTime);
            }
            
            List<AggQrcode> list = qrCodeService.selectAggQrcodeList(query);
            PageInfo<AggQrcode> pageInfo = new PageInfo<>(list);
            
            return AjaxResult.success(pageInfo);
        }
        catch (Exception e)
        {
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * 聚合码详情
     */
    @GetMapping("/detail")
    public AjaxResult detail(@RequestParam Long id)
    {
        try
        {
            AggQrcode aggQrcode = qrCodeService.selectAggQrcodeById(id);
            if (aggQrcode == null)
            {
                return AjaxResult.error("聚合码不存在");
            }
            return AjaxResult.success(aggQrcode);
        }
        catch (Exception e)
        {
            return AjaxResult.error(e.getMessage());
        }
    }
}


